import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { dataSourceConfig } from '@/config'
import { mockRequest, mockResponse } from '@/mock'

/**
 * 创建axios实例
 */
const request = axios.create({
  baseURL: '/api',
  timeout: dataSourceConfig.apiTimeout
})

/**
 * 请求拦截器
 */
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token等认证信息
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截器
 */
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 添加响应日志
    console.log('API Response:', response.data)
    
    // 直接返回数据
    return response.data
  },
  (error: any) => {
    // 添加错误日志
    console.error('API Error:', error)
    
    // 处理错误响应
    if (error.response) {
      const message = error.response.data?.message || '请求失败'
      return Promise.reject(new Error(message))
    }
    
    return Promise.reject(error)
  }
)

/**
 * 统一的请求方法
 * @param url 请求地址
 * @param method 请求方法
 * @param data 请求数据
 * @param mockData mock数据
 * @param config 额外的axios配置
 * @returns Promise
 */
export const http = async <T>(
  url: string,
  method: 'get' | 'post' | 'put' | 'delete' | 'patch' = 'get',
  data?: any,
  mockData?: T,
  config?: Partial<InternalAxiosRequestConfig>
): Promise<T> => {
  // 如果使用mock数据
  if (dataSourceConfig.useMockData && mockData !== undefined) {
    return mockRequest(mockData)
  }

  // 使用真实API
  try {
    const response = await request({
      url,
      method,
      data: method === 'get' ? undefined : data,
      params: method === 'get' ? data : undefined,
      ...config
    })
    return response.data
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 统一的响应格式
 */
export const response = {
  success: (data: any) => mockResponse.success(data),
  error: (message: string, code = 500) => mockResponse.error(message, code)
} 